package chances.epg.data.service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import chances.epg.data.PageBean;
import chances.epg.data.ibatis.PageRowBounds;

@Service
public class EpgUpdateService {

	@Autowired
	protected SqlSessionTemplate epgDBClient;

	protected Map<String, Integer> categoryCount = new ConcurrentHashMap<String, Integer>();

	private int lastHour = 24;

	/**
	 * 
	 * @param statementId
	 * @return
	 */
	public List<?> queryForList(String statementId) {
		return this.epgDBClient.selectList(statementId);
	}

	/**
	 * 
	 * @param queryName
	 * @param paramsMap
	 * @return
	 */
	public List<?> queryForList(String statementId, Map<String, Object> paramsMap) {
		return this.epgDBClient.selectList(statementId, paramsMap);
	}

	/**
	 * 
	 * @param queryName
	 * @param paramsMap
	 * @param size
	 * @return
	 */
	public List<?> queryForList(String statementId, Map<String, Object> paramsMap, int start, int size) {
		PageRowBounds bounds = new PageRowBounds();
		bounds.setStart(start);
		bounds.setPageSize(size);
		return this.epgDBClient.selectList(statementId, paramsMap, bounds);
	}

	/**
	 * 
	 * @param queryName
	 * @param paramsMap
	 * @param pageBean
	 * @return
	 */
	public List<?> queryForList(String statementId, Map<String, Object> paramsMap, int start, PageBean pageBean) {
		PageRowBounds bounds = new PageRowBounds();
		bounds.setStart(start);
		bounds.setPageSize(pageBean.getPageSize());
		bounds.setPageNo(pageBean.getCurrentPage());

		List<?> result = this.epgDBClient.selectList(statementId, paramsMap, bounds);
		pageBean.setRecordCount(bounds.getRecordCount());
		return result;
	}

	public Map<String, Integer> getCategoryCount(String[] array) {
		Map<String, Integer> result = new HashMap<String, Integer>();
		for (String str : array) {
			try {
				int updateNum = categoryCount.get(str);
				result.put(str, updateNum);
			} catch (Exception e) {
				continue;
			}
		}
		return result;
	}

	public void queryCategoryCount() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, 0 - this.getLastHour());
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("updateTime", calendar.getTime());

		List<Map<String, Object>> result = this.epgDBClient.selectList("listCategoryCount", paramsMap);
		for (Map<String, Object> temp : result) {
			String count = temp.get("count") + "";
			categoryCount.put((String) temp.get("categoryCode"), Integer.parseInt(count));
		}
	}

	public int getLastHour() {
		return lastHour;
	}

	public void setLastHour(int lastHour) {
		this.lastHour = lastHour;
	}

}
